import dayjs from 'dayjs'
import JSZip from 'jszip'

/**
 * 获取图片的原始信息
 */
export const getImageInfo = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        resolve(img)
      }
    }
    reader.readAsDataURL(file)
  })
}
/**
 * base64 转二进制
 */
export const base64ToBlob = base64 => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

/**
 * 获取图片的base64
 * @param {*} file 图片文件
 * @param {*} callback 回调函数
 */
export const blobToBase64 = blob => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => resolve(e.target.result)
    reader.readAsDataURL(blob)
  })
}

/**
 * 压缩图片
 *
 * 暂时无法压缩png格式
 * 后期改为使用”imagemin“插件去压缩
 */
export const compressImage = (file, config = {}) => {
  // 默认配置
  const defaultConfig = {
    zoom: 1,
    imageType: 'image/png',
    quality: null,
    fillStyle: !/png/.test(config.imageType) ? '#fff' : 'transparent',
    ...config
  }
  try {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.addEventListener('load', () => {
        const img = new Image()
        img.addEventListener('load', () => {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          const { width, height } = img

          // 是否需要缩放
          const MAX_WIDTH = width * defaultConfig.zoom
          const MAX_HEIGHT = height * defaultConfig.zoom

          canvas.width = MAX_WIDTH
          canvas.height = MAX_HEIGHT

          ctx.fillStyle = defaultConfig.fillStyle
          ctx.clearRect(0, 0, MAX_WIDTH, MAX_HEIGHT)
          ctx.fillRect(0, 0, MAX_WIDTH, MAX_HEIGHT)
          ctx.drawImage(img, 0, 0, MAX_WIDTH, MAX_HEIGHT)

          const base64 = canvas.toDataURL(
            defaultConfig.imageType,
            defaultConfig.quality
          )

          if (base64.length < 10) {
            var err = new Error('生成base64失败')
            reject(err)
            throw err
          }
          resolve(base64)
        })
        img.src = reader.result
      })
      reader.readAsDataURL(file)
    })
  } catch (error) {
    console.error(error)
    throw error
  }
}

/**
 * 本地下载文件
 */
export const downloadFile = (base64, fileName) => {
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = base64
  a.download = fileName
  a.click()
}

/**
 * 打包zip下载文件
 */
export const downloadZip = list => {
  const zip = new JSZip()
  list.forEach(item => {
    zip.file(
      item.name,
      item.base64.replace(/^data:image\/(png|jpg|jpeg|x-icon);base64,/, ''),
      { base64: true }
    )
  })

  // 生成压缩包并将其下载到本地
  zip.generateAsync({ type: 'blob' }).then(content => {
    const link = document.createElement('a')
    link.href = URL.createObjectURL(content)
    link.download = `${dayjs().format('YYYY-MM-DD') + dayjs()}.zip`
    link.click()
  })
}
/**
 * 图片转ico/icon
 */
export const imgToIcon = (file, options) => {
  const config = {
    size: null,
    ...options
  }
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader()
      reader.addEventListener('load', () => {
        const img = new Image()
        img.addEventListener('load', async () => {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')

          // 是否需要缩放
          const MAX_WIDTH = config.size
          const MAX_HEIGHT = config.size

          canvas.width = MAX_WIDTH
          canvas.height = MAX_HEIGHT

          ctx.fillStyle = 'transparent'
          ctx.clearRect(0, 0, MAX_WIDTH, MAX_HEIGHT)
          ctx.fillRect(0, 0, MAX_WIDTH, MAX_HEIGHT)
          ctx.drawImage(img, 0, 0, MAX_WIDTH, MAX_HEIGHT)

          // 将图片转换为 base64 编码
          const base64 = canvas.toDataURL('image/png')

          // 将 base64 编码转换为 .ico 数据
          const icoData = Buffer.from(base64.split(',')[1], 'base64')

          // 将 .ico 数据保存到文件
          const file = new File([icoData], 'icon.ico', { type: 'image/x-icon' })
          const iconFile = await blobToBase64(file)

          if (iconFile.length < 10) {
            var err = new Error('生成iconFile失败')
            reject(err)
            throw err
          }
          resolve(iconFile)
        })
        img.src = reader.result
      })
      reader.readAsDataURL(file)
    } catch (error) {
      reject(error)
      console.error(error)
      throw new Error(error)
    }
  })
}
